package cn.fqb.controller;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cn.fqb.util.AppConfig;
import com.renren.api.client.RenrenApiClient;

@Controller
public class TuzhiController {

    @RequestMapping(value = "/home", method = { RequestMethod.GET, RequestMethod.POST })
    public void home(String xn_sig_session_key, String xn_sig_user, Model model) {
        getFriendsList(xn_sig_session_key, xn_sig_user, model);
        model.addAttribute("appId", AppConfig.APP_ID);
    }

    public void getFriendsList(String sessionKey, String renrenUserId, Model model) {
        if (sessionKey != null && renrenUserId != null) {
            RenrenApiClient apiClient = new RenrenApiClient(sessionKey);
            JSONArray userInfo = apiClient.getUserService().getInfo(renrenUserId, "name,headurl");
            if (userInfo != null && userInfo.size() > 0) {
                JSONObject currentUser = (JSONObject) userInfo.get(0);
                if (currentUser != null) {
                    String userName = (String) currentUser.get("name");
                    String userHead = (String) currentUser.get("headurl");
                    model.addAttribute("userName", userName);
                    model.addAttribute("userHead", userHead);
                }
            }
            // 获取好友列表数据
            JSONArray friendsList = apiClient.getFriendsService().getFriends(1, 30);// 最多取30个好友
            model.addAttribute("friendsList", friendsList);
        }
    }
}